<?php
declare(strict_types=1);


namespace App\Middleware;

use App\Exception\BusinessException;
use App\Log;
use App\Utils\Helper;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Phper666\JWTAuth\Exception\JWTException;
use Phper666\JWTAuth\Exception\TokenValidException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Constants\ErrorCode;

/**
 * 统一响应json中间件, (可选)
 * Class ApiResponseMiddleware
 * @package App\Middleware
 */
class ApiResponseMiddleware implements MiddlewareInterface
{
    // Response返回数据
    // 1. 支持返回多种数据格式（json, xml, protobuf, packMsg）
    // 2. 可以自定义返回数据格式
    // 3. 不写日志
    // 4. 捕获不同的异常

    /**
     * @Inject()
     * @var HttpResponse
     */
    protected $response;

    /**
     * Notes: 获取控制器响应 做json处理
     * User: 陈朋
     * DateTime: 2021/6/30 18:45
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $body = json_decode($handler->handle($request)->getBody()->getContents(), true);
        if (isset($body['error_code'])) {
            abort($body['error_code']);
        }
        // 返回为空的code
        if (empty($body)) {
            abort(ErrorCode::SUCCESS_NO_DATA);
        }

        return Helper::respondSuccess($body);
    }
}
